import React, { Component } from 'react';
import { Form, InputNumber, message, Radio, Select } from 'antd';
import { isArray, isEmpty, isFunction, omit } from 'lodash';
import { isObjectValEqual } from '/common/utils/utils';
import { jsonPost } from '@/helpers/request';
import { formatFilter } from '/common/utils/queryUtils';
import ButtonComp from '/common/componentsTpl/ButtonComp';
import ModalComp from '/common/components/ModalItem/ModalComp';

const { Option } = Select;

function dealIdFilter(selectedKeys) {
  return formatFilter({
    filterData: {
      id: {
        expression: 'IN',
        value: isArray(selectedKeys) ? selectedKeys.join(',') : selectedKeys,
      },
    },
  });
}


const printMarginObj = {
  FP: [9, 12, 25, 10],
  A42B_mid: [14, 15, 25, 10],
  A42B_top: [9, 9, 25, 10],
  A43B: [5, 8, 25, 10],
  a4_w: [9, 9, 25, 10],
  a5: [14, 15, 25, 10],
};

class PrintMargin extends Component {

  state = {};

  marginArr = [
    { cn: '上', fieldName: 'marginTop' },
    {
      cn: '下', fieldName: 'marginBottom',
      // disabled: true
    },
    { cn: '左', fieldName: 'marginLeft' },
    {
      cn: '右', fieldName: 'marginRight',
      // disabled: true
    },
  ];

  componentDidMount() {
    this.setFormValues();
  }

  componentDidUpdate(prevProps, prevState) {
    if (!isObjectValEqual(this.props, prevProps)) {
      this.setFormValues();
    }
  }

  setFormValues() {
    const { pageSizeType, paperDirection, form } = this.props;
    let pKey = 'A42B' === pageSizeType ? `${pageSizeType}_${paperDirection}` : pageSizeType;
    const pMagrinArr = printMarginObj[pKey] || [];

    if (!isEmpty(pMagrinArr)) {
      form.setFieldsValue({
        marginTop: pMagrinArr[0],
        marginBottom: pMagrinArr[1],
        marginLeft: pMagrinArr[2],
        marginRight: pMagrinArr[3],
      });
    }
  }

  handleNumberChange(fieldName, value) {
    // console.log('changeNum', value);
    // const { form } = this.props;
    // let val = value;
    //
    // if (null !== value && isNaN(value)) {
    //   let tmpO = {};
    //   tmpO[fieldName] = '';
    //   form.setFieldsValue(tmpO);
    // }

  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const inputStyle = { width: 60, margin: '0 8px', color: '#666' },
      itemStyle = { width: '50%', display: 'inline-block' };

    return this.marginArr.map((v, k) => {
      let props = v.disabled ? { disabled: true } : {};
      return (
        <Form.Item
          key={v.fieldName}
          style={itemStyle}
        >
          <span>{v.cn}</span>
          {getFieldDecorator(v.fieldName)(
            <InputNumber onChange={this.handleNumberChange.bind(this, v.fieldName)} style={inputStyle} {...props}/>,
          )}
          <span>毫米</span>
        </Form.Item>
      );
    });
  }
}

@Form.create()
class PrintForm extends Component {
  state = {};

  componentDidMount() {
    this.props.onRef && this.props.onRef(this);
  }


  getAjaxData() {
    return this.props.form.getFieldsValue();
  }

  /**
   * 打印纸张改变之后
   * @param e
   */
  handleChangePaperType(e) {
    // console.log(e);
    // const value = e.target.value;
    // if ('A42B' === value || 'A43B' === value) {
    //   // 打印方向：纵向
    //   this.props.form.setFieldsValue({ direction: 'Z' });
    // } else {
    //   // 打印方向：横向
    //   this.props.form.setFieldsValue({ direction: 'H' });
    // }
  }

  /**
   * 改变纸张的方向之后
   * @param val
   */
  handleChangePD(val) {
    // console.log(val);
  }

  render() {
    const { form, itemId } = this.props;
    const { getFieldDecorator } = form;
    const pageSizeType = form.getFieldValue('pageSizeType') || 'A42B';
    const radioStyle = { display: 'block', marginTop: 5, marginBottom: 8 };

    return (
      <Form layout="horizontal" labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}>
        {
          itemId > 0?null:(
            <Form.Item label='打印选项'>
              {getFieldDecorator('printType', {
                initialValue: '1',
              })(
                <Radio.Group>
                  <Radio value="1" className={'mr16'}>打印全部</Radio>
                  <Radio value="2" disabled={isEmpty(this.props.selectedKeys)}>打印选中</Radio>
                </Radio.Group>,
              )}
            </Form.Item>
          )
        }
        <Form.Item label='选择纸张'>
          {getFieldDecorator('pageSizeType', {
            initialValue: 'A42B',
          })(
            <Radio.Group onChange={this.handleChangePaperType.bind(this)}>
              <Radio style={radioStyle} value="FP" className={'mr16'}>发票版 140毫米*240毫米 <span
                className={'text-danger'}>(推荐)</span></Radio>
              <Radio style={radioStyle} value="A42B">A4两版 <span className={'text-danger'}>(推荐)</span></Radio>
              <Radio style={radioStyle} value="A43B">A4三版</Radio>
              {/*<Radio style={radioStyle} value="a4_w">A4宽 120毫米*210毫米</Radio>*/}
              {/*<Radio style={radioStyle} value="a5">A5</Radio>*/}
            </Radio.Group>,
          )}
        </Form.Item>
        {/*<div style={'A42B' !== form.getFieldValue('pageSizeType') ? { display: 'none' } :*/}
        {/*  {*/}
        {/*    display: 'inline-block',*/}
        {/*    position: 'absolute',*/}
        {/*    top: '88px',*/}
        {/*    right: '150px',*/}
        {/*  }*/}
        {/*}>*/}
        {/*  {getFieldDecorator('paperDirection', {*/}
        {/*    initialValue: 'mid',*/}
        {/*  })(*/}
        {/*    <Select onChange={this.handleChangePD.bind(this)}>*/}
        {/*      <Option value={'mid'}>居中</Option>*/}
        {/*      <Option value={'top'}>靠上</Option>*/}
        {/*    </Select>,*/}
        {/*  )}*/}
        {/*</div>*/}
        {/*<Form.Item label='打印方向'>*/}
        {/*  {getFieldDecorator('direction', {*/}
        {/*    initialValue: 'A42B' === pageSizeType || 'A43B' === pageSizeType ? 'Z' : 'H',*/}
        {/*  })(*/}
        {/*    <Radio.Group disabled={'A42B' === pageSizeType || 'A43B' === pageSizeType}>*/}
        {/*      <Radio value="Z" className={'mr16'}><span className={'text-black'}>纵向排版</span></Radio>*/}
        {/*      <Radio value="H"><span className={'text-black'}>横向排版</span></Radio>*/}
        {/*    </Radio.Group>,*/}
        {/*  )}*/}
        {/*</Form.Item>*/}
        {/*<Form.Item label='页面边距' style={{ marginBottom: 0 }}>*/}
        {/*  <PrintMargin form={form}*/}
        {/*               pageSizeType={form.getFieldValue('pageSizeType')}*/}
        {/*               paperDirection={form.getFieldValue('paperDirection')}*/}
        {/*  />*/}
        {/*</Form.Item>*/}
        {/*<Form.Item label='其他选项'>*/}
        {/*  {getFieldDecorator('others', {*/}
        {/*    initialValue: ['1', '2'],*/}
        {/*  })(*/}
        {/*    <Checkbox.Group style={{ width: '100%', marginTop: 5 }}>*/}
        {/*      <Row>*/}
        {/*        <Col span={8}>*/}
        {/*          <Checkbox value="1">打印制单人</Checkbox>*/}
        {/*        </Col>*/}
        {/*        <Col span={8}>*/}
        {/*          <Checkbox value="2">*/}
        {/*            打印审核人*/}
        {/*          </Checkbox>*/}
        {/*        </Col>*/}
        {/*        <Col span={8}>*/}
        {/*          <Checkbox value="3">打印封面</Checkbox>*/}
        {/*        </Col>*/}
        {/*      </Row>*/}
        {/*    </Checkbox.Group>,*/}
        {/*  )}*/}
        {/*</Form.Item>*/}

      </Form>
    );
  }
}

class PrintComp extends Component {
  state = {
    loading: false,
    isShowModal: false,
  };

  clickPrint() {
    if (this.props.needModal) {
      this.setState({ isShowModal: true });
    } else {
      this._print();
    }
  }

  clickCancel() {
    this.setState({ isShowModal: false });
  }

  /**
   * 点击确认打印
   */
  clickConfirm() {
    if (this.formRef && isFunction(this.formRef.getAjaxData)) {
      this._print(this.formRef.getAjaxData());
    }
  }

  _print(values = {}) {
    const searchData = this.props.params;
    const selectedKeys = this.props.selectedKeys;
    console.log('values', values);
    let ajaxData = {};

    // 单个打印
    if (this.props.itemId > 0) {
      ajaxData = dealIdFilter([this.props.itemId]);

    } else {
      // 导出全部
      if (1 == values.printType && !isEmpty(searchData)) {
        ajaxData = formatFilter(searchData);
      }
      // 导出选中
      else {
        if (!isEmpty(selectedKeys)) {
          ajaxData = dealIdFilter(selectedKeys);
        } else {
          message.warning('无选中记录');
          return;
        }
      }
    }
    console.log('ajaxData', ajaxData);

    this.setState({ loading: true });
    jsonPost(this.props.api, ajaxData, {
      params: omit(values, ['printType'])
    }).then(rsp => {
      this.setState({ loading: false });
      if (rsp && 200 === rsp.status && rsp.data) {
        window.open(rsp.data);
      }
    });
  }

  render() {
    const { modalProps, cn, appCode, itemId } = this.props;
    const imProps = {
      visible: this.state.isShowModal, // 是否显示
      loading: this.state.loading, // 是否正在加载
      title: `打印设置`,
      bodyStyle: { padding: 16 },
      onCancel: this.clickCancel.bind(this), // 点击取消后的回调
      onOk: this.clickConfirm.bind(this),
      ...modalProps,
    };
    const btnLoading = !this.props.needModal && this.state.loading;
    const btnDisabled = this.props.disabled || btnLoading;
    return (
      <>
        {
          'button' === this.props.btnType ? (
            <ButtonComp actionType={'exportPdf'} disabled={btnDisabled} loading={btnLoading}
                        onClick={this.clickPrint.bind(this)}>打印</ButtonComp>
          ) : (
            <ButtonComp actionType={'exportPdf'} btnType={'a'} disabled={btnDisabled}
                        onClick={this.clickPrint.bind(this)}>
              {btnLoading ? '打印中...' : '打印'}
            </ButtonComp>
          )
        }
        <ModalComp {...imProps}>
          <PrintForm
            onRef={(ref) => {
              this.formRef = ref;
            }}
            appCode={appCode}
            itemId={itemId}
            cn={cn}
            selectedKeys={this.props.selectedKeys}
          />
        </ModalComp>
      </>
    );
  }
}

PrintComp.defaultProps = {
  api: '',
  params: {},
  selectedKeys: [],
  needModal: true,
  itemId: 0, // Number 当此字段有值的时候，表示是单个打印，字段值为 id 值
  disabled: false,
  btnType: 'button', // String 打印按钮的类型；'button'：按钮；'a'：a 标签
};

export default PrintComp;
